$(function () {

    $("#jqGrid").jqGrid({
        url: '../dictemployee/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', width: 50, key: true,hidden:true },
			{ label: '姓名', name: 'name', width: 60,align:"center" }, 			
			{ label: '出生日期', name: 'birthday', width: 80, align:"center",formatter: function(value, options, row){
				return value.substring(0,10)} }, 			
			{ label: '性别', name: 'gender', width: 50,align:"center",formatter: function(value, options, row){
				return value === true ? 
						'<span class="label label-primary">男</span>' : 
						'<span class="label label-info">女</span>';
				}}, 			
			{ label: '身份证号', name: 'cardno',align:"center", width: 80 ,hidden:true}, 			
			{ label: '员工编号', name: 'workno', align:"center",width: 160 },
/*			{ label: '上级工号', name: 'upWorkNo', width: 80},*/
			{ label: '职位编号', name: 'jobNo', align:"center",width: 80}, 
			{ label: '职位名称', name: 'jobName',align:"center", width: 130 }, 				
			{ label: '部门编号', name: 'deptno',align:"center", width: 80,hidden:true },
			{ label: '部门名称', name: 'deptName',align:"center", width: 80 },
			{ label: 'sys_user的id字段', name: 'userid', width: 80,hidden:true }, 
			{ label: '用户名称', name: 'userName',align:"center", width: 80},
			{ label: '入职时间', name: 'inorgtime',align:"center", width: 80, formatter: function(value, options, row){
				return value.substring(0,10)} }, 			
			{ label: '转正时间', name: 'zztime',align:"center", width: 80, formatter: function(value, options, row){
				if(value!=undefined){
					return value.substring(0,10)
				}else{
					return ""
				}
				 }}, 			
			{ label: '离职时间', name: 'outorgtime',align:"center", width: 80, formatter: function(value, options, row){
				if(value!=null){
					return value.substring(0,10)
				}
				return ""} }, 			
			{ label: '手机', name: 'hasorgmobile',align:"center", width: 60,formatter: function(value, options, row){
				return value === 1 ? 
						'<span class="label label-primary">是</span>' : 
						'<span class="label label-info">否</span>';
				} },
			{ label: '端口', name: 'hasports',align:"center", width: 60,formatter: function(value, options, row){
					return value === 1 ? 
							'<span class="label label-primary">是</span>' : 
							'<span class="label label-info">否</span>';
					} }, 
			{ label: '手机号码', name: 'mobileno',align:"center", width: 100 }, 			
			{ label: '推荐人', name: 'recommender',align:"center", width: 80 }, 			
			{ label: '排序', name: 'orderno', width: 80,hidden:true }, 			
			{ label: '备注', name: 'memo', width: 80,hidden:true  }, 			
			/*{ label: 'b备注字段', name: 'excol', width: 80 }, 		*/	
			{ label: '创建时间', name: 'createtime', width: 80,hidden:true }, 			
			{ label: '创建人', name: 'createby', width: 80,hidden:true }, 			
			{ label: '修改时间', name: 'updatetime', width: 80,hidden:true }, 			
			{ label: '修改人', name: 'updateby', width: 80,hidden:true }, 			
			{ label: '状态', name: 'state', width: 80,hidden:true, formatter: function(value, options, row){
				return value === true ? 
						'<span class="label label-danger">禁用</span>' : 
						'<span class="label label-success">正常</span>';
				} }			
        ],
		viewrecords: true,
		height: $(window).height()-120,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var setting = {
		data: {
			
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "fid",
				rootPId: -1
			},
			key: {
				url:"nourl"
			}
		}
	};
	var ztree;


var vm = new Vue({
	el:'#rrapp',
	data:{
		value:null,
		showList: true,
		title: null,
		dictEmployee: {},
		dept:{
			parentName:null,
			fid:0,
			type:1,
			orderNum:0
		}
	},
	methods: {
		getDept: function(deptId){
			//加载菜单树
			$.get("../dictdepartment/orderlist", function(r){
				ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
				var node = ztree.getNodeByParam("id", vm.dept.fid);
				ztree.selectNode(node);
				
				vm.dept.parentName = node.name;
			})
		},
		deptTree: function(){
			layer.open({
				type: 1,
				offset: '50px',
				skin: 'layui-layer-molv',
				title: "选择部门",
				area: ['300px', '450px'],
				shade: 0,
				shadeClose: false,
				content: jQuery("#deptLayer"),
				btn: ['确定', '取消'],
				btn1: function (index) {
					var node = ztree.getSelectedNodes();
					//选择上级菜单
					vm.dictEmployee.deptno = node[0].id;
					vm.dictEmployee.deptName=node[0].name;	
					layer.close(index);
	       }
			
			});
		},
		imp: function(){      
		    //检验导入的文件是否为Excel文件     
		    	$("#uploadFile").click();		    		
		    	$("#sure").show(); 		   
		} ,
		up: function () {
			$("#sure").hide();
			var uploadFile = document.getElementById("uploadFile").value;      
	    	if(uploadFile == null || uploadFile == ''){      
	    		alert("请选择要上传的Excel文件");      
	    		return;      
	    	}else{      
	    		var fileExtend = uploadFile.substring(uploadFile.lastIndexOf('.')).toLowerCase();       
	    		if(fileExtend == '.xls'||fileExtend == '.xlsx'){    
	    			    var formData = new FormData();
	    			    var name = $("#uploadFile").val();
	    			    formData.append("file",$("#uploadFile")[0].files[0]);
	    			    formData.append("name",name);
	    			    $.ajax({
	    			        url : '../dictemployee/upload',
	    			        type : 'POST',
	    			        async : false,
	    			        data : formData,
	    			        // 告诉jQuery不要去处理发送的数据
	    			        processData : false,
	    			        // 告诉jQuery不要去设置Content-Type请求头
	    			        contentType : false,
	    			        beforeSend:function(){
	    			            console.log("正在进行，请稍候");
	    			        },
	    			        success : function(responseStr) {
	    			            if(responseStr==10){
	    			                alert("导入成功");
	    			                vm.reload();
	    			            }else if(responseStr==20){
	    			                alert("对不起，请先将当前数据存为历史");
	    			            }else{
	    			            	alert("导入失败");
	    			            }
	    			        }
	    			    });
	    		}else{      
	    			alert("文件格式需为'.xls'格式");      
	    			return;      
	    		}      
	    	}      
	    	//提交表单       
		},
		his: function () {			
				alert("存为历史将不可变更");
				$("#surehis").show(); 
				$("#inorgtime").css("display","inline"); 
				
		},
		surehis: function () {
			var time = $("#inorgtime").val();
			if($("#inorgtime").val()==""){
				alert("请选择时间");				
			}else{
				$.ajax({
					type: "GET",
				    url: '../dictdepartment/hashis',
				    data:"time="+time,
				    success: function(r){
				    	if(r.code === 0){
				    		$.ajax({
								type: "GET",
							    url: '../dictemployee/hashisdata',
							    data:"time="+time,
							    success: function(r){
							    	if(r.code === 0){
							    		$.ajax({
											type: "GET",
										    url: '../dictemployee/history',
										    data:"time="+time,
										    success: function(r){
										    	if(r.code === 0){
													alert('操作成功', function(){
														$("#surehis").hide(); 
														$("#inorgtime").hide(); 
													});
												}else{
													alert(r.msg);
												}
											}
										});
							    	}else{
										confirm("已有当月历史，继续将会覆盖已有历史",function(){
											$.ajax({
											type: "GET",
										    url: '../dictemployee/history',
										    data:"time="+time,
										    success: function(r){
										    	if(r.code === 0){
													alert('操作成功', function(){
														$("#surehis").hide(); 
														$("#inorgtime").hide(); 
													});
												}else{
													alert(r.msg);
												}
											}
										});
										})
									}
								}
							});
				    	}else{
							alert("对不起该月份的部门尚未成为历史");
						}
					}
				});
				
			}	
		},
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dictEmployee = {
					deptno:"",
					deptName:"",
					gender:true,
					hasorgmobile:true,
					state:true
			};
			
			vm.dept = {parentName:null,fid:0,type:1,orderNum:0};
			vm.getDept();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.getDept();
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.dictEmployee.id == null ? "../dictemployee/save" : "../dictemployee/update";
			vm.dictEmployee.birthday = $("#birthday").val();			
			vm.dictEmployee.inorgtime = $("#inorgtime").val();
			vm.dictEmployee.zztime = $("#zztime").val();
			vm.dictEmployee.outorgtime = $("#outorgtime").val();
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.dictEmployee),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../dictemployee/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get("../dictemployee/infoxtd/"+id, function(r){
                vm.dictEmployee = r.dictEmployeeXtd;
                
                vm.dictEmployee.birthday = vm.dictEmployee.birthday.substring(0,10);
                vm.dictEmployee.inorgtime = vm.dictEmployee.inorgtime.substring(0,10);
                vm.dictEmployee.zztime = vm.dictEmployee.zztime.substring(0,10);
                vm.dictEmployee.outorgtime = vm.dictEmployee.outorgtime.substring(0,10);
               
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'value': vm.value},
                page:page
            }).trigger("reloadGrid");
		},
		getUserList:function(){
			var arrayNewList = new Array();
			var columnCont = new Array();
			$('#cfqgrid').jqGrid({
    	        url: '../sys/user/list',
    	        datatype: "json",
    	        colModel: [			
    				{ label: 'userId', name: 'userId', width: 50, key: true,hidden:true},
    				{ label: '用户名', name: 'username', width: 80 }, 			
    				{ label: '邮箱', name: 'email', width: 80 }, 			
    				{ label: '联系方式', name: 'mobile', width: 80 }							
    	        ],
    	        viewrecords: true,
		        height: window.screen.availHeight-250,
		        rowNum: 10,
				rowList : [10,30,50],
		        rownumbers: true, 
		        rownumWidth: 50, 
		        width:window.screen.availWidth-250,  
		        autowidth: false,  
		        shrinkToFit: true,
		        multiselect: true,
    	        pager: "#jqGridPagercf",
    	        jsonReader : {
    	            root: "page.list",
    	            page: "page.currPage",
    	            total: "page.totalPage",
    	            records: "page.totalCount"
    	        },
    	        prmNames : {
    	            page:"page", 
    	            rows:"limit", 
    	            order: "order"
    	        },
    	        onSelectAll:function(aRowids,status){
		            if(status==true){
		                //循环aRowids数组，将code放入arrayNewList数组中
		                $.each(aRowids,function(i,item){
		                   saveData(item);
		                })
		            }else{
		                //循环aRowids数组，将code从arrayNewList中删除
		                $.each(aRowids,function(i,item){
		                   deleteIndexData(item);
		                })
		            }

		        },
		        onSelectRow:function(aRowids,status){
		            if(status==true){
		               saveData(aRowids);
		            }else{
		               deleteIndexData(aRowids);
		            }

		        },
    	        gridComplete:function(){
    	        	//隐藏grid底部滚动条
    	        	$("#cfqgrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
    	        	layer.open({
    	        		type : 1,
//    	        		offset:'50px',
    	        		title : "用户列表",
    	        		closeBtn :1,  
    	        		maxmin:1,
    	        		btn : [ '确认', '取消' ],
    	        		area : [ "100%", "100%" ],
    	        		skin : 'layui-layer-molv', // 
    	        		shade:0,
    	        		shadeClose : false,
    	        		content : $('#managerName'),
    	        		cancel: function(index, layero){ 
    	        			arrayNewList=[];
		        			columnCont=[];
    	        			layer.close(index)
    	        			  
    	        			},
    	        			
    	    			btn2: function(index, layero){
    	        			arrayNewList=[];
		        			columnCont=[];
    	        			layer.close(index)
    	        			  
    	        			},
    	        		yes:function(index,layero){
    	        			if(arrayNewList.length==0){
		        				alert('请选择一条记录');
		        				return ;
		        			}
		        			if(arrayNewList.length>1){
		        				alert('只能选择一条记录');
		        				return ;
		        			}
		        		    var entrailsid=arrayNewList.join(",")
		        			var entrailsname=columnCont.join(",");
		        			
		        			if(arrayNewList==undefined){
		        				
		        				vm.dictEmployee.userid="";
		        			}else{
		        				vm.dictEmployee.userid=entrailsid;
		        				
		        			}
		        			if(columnCont==undefined){
		        				vm.dictEmployee.userName="";
		        				
		        			}else{
		        				vm.dictEmployee.userName=entrailsname;
		        				
		        			}
		        			$('#userName').val(entrailsname);
		        			
		        			if(arrayNewList.length!=0){
		        				arrayNewList=[];
		        				columnCont=[];
		        			layer.close(index); 
		        			}
    	        		  }
    	        	});
    	        }
    	    });
			function saveData(obj){
				var rowData = $("#cfqgrid").jqGrid("getRowData", obj);
	            arrayNewList.push(rowData.userId);
	            columnCont.push(rowData.username);
	        }
			
	        function deleteIndexData(obj){
	        	var rowData = $("#cfqgrid").jqGrid("getRowData", obj);
	            //获取obj在arrayNewList数组中的索引值
	            for(i = 0; i < arrayNewList.length; i++){
	                if (arrayNewList[i] == rowData.userId){
	                    //根据索引值删除arrayNewList中的数据
	                	RemoveValByIndex(arrayNewList, i);
	                	RemoveValByIndex(columnCont, i);
	                    i--;
	                }
	             }
	        }
	        $("#cfqgrid").jqGrid('clearGridData');
			$("#cfqgrid").trigger('reloadGrid');
		},
		
		getDutyList:function(){
			var arrayNewList = new Array();
			var columnCont = new Array();
			$('#zjJobId').jqGrid({
    	        url: '../dictjob/list',
    	        datatype: "json",
    	        colModel: [			
    	        	{ label: 'id', name: 'id',hidden:true, width: 50, key: true ,hidden:true},
    				{ label: '编号', name: 'jobno', width: 80 }, 
    				{ label: '名称', name: 'name', width: 80 }, 			   							
    				{ label: '排序', name: 'orderno', width: 80,hidden:true }, 					
    				{ label: '备注', name: 'memo', width: 80 }, 						
    				{ label: '状态', name: 'state', width: 80, formatter: function(value, options, row){
    					return value === false ? 
    							'<span class="label label-danger">禁用</span>' : 
    							'<span class="label label-success">正常</span>';
    					} }	
    	        ],
    	        viewrecords: true,
		        height: window.screen.availHeight-250,
		        rowNum: 10,
				rowList : [10,30,50],
		        rownumbers: true, 
		        rownumWidth: 50, 
		        width:window.screen.availWidth-250,  
		        autowidth: false,  
		        shrinkToFit: true,
		        multiselect: true,
    	        pager: "#jqGridPagercf",
    	        jsonReader : {
    	            root: "page.list",
    	            page: "page.currPage",
    	            total: "page.totalPage",
    	            records: "page.totalCount"
    	        },
    	        prmNames : {
    	            page:"page", 
    	            rows:"limit", 
    	            order: "order"
    	        },
    	        onSelectAll:function(aRowids,status){
		            if(status==true){
		                //循环aRowids数组，将code放入arrayNewList数组中
		                $.each(aRowids,function(i,item){
		                   saveData(item);
		                })
		            }else{
		                //循环aRowids数组，将code从arrayNewList中删除
		                $.each(aRowids,function(i,item){
		                   deleteIndexData(item);
		                })
		            }

		        },
		        onSelectRow:function(aRowids,status){
		            if(status==true){
		               saveData(aRowids);
		            }else{
		               deleteIndexData(aRowids);
		            }

		        },
    	        gridComplete:function(){
    	        	//隐藏grid底部滚动条
    	        	$("#zjJobId").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
    	        	layer.open({
    	        		type : 1,
//    	        		offset:'50px',
    	        		title : "岗位列表",
    	        		closeBtn :1,  
    	        		maxmin:1,
    	        		btn : [ '确认', '取消' ],
    	        		area : [ "100%", "100%" ],
    	        		skin : 'layui-layer-molv', // 
    	        		shade:0,
    	        		shadeClose : false,
    	        		content : $('#zjJobName'),
    	        		cancel: function(index, layero){ 
    	        			arrayNewList=[];
		        			columnCont=[];
    	        			layer.close(index)
    	        			  
    	        			},
    	    			
    	        		yes:function(index,layero){
    	        			if(arrayNewList.length==0){
		        				alert('请选择一条记录');
		        				return ;
		        			}
		        			if(arrayNewList.length>1){
		        				alert('只能选择一条记录');
		        				return ;
		        			}
		        		    var entrailsid=arrayNewList.join(",")
		        			var entrailsname=columnCont.join(",");
		        			
		        			if(arrayNewList==undefined){
		        				vm.dictEmployee.jobno="";
		        				
		        			}else{
		        				vm.dictEmployee.jobno=entrailsid;
		        				
		        			}
		        			if(columnCont==undefined){
		        				vm.dictEmployee.jobName="";
		        				
		        			}else{
		        				vm.dictEmployee.jobName=entrailsname;
		        				
		        			}
		        			$('#jobName').val(entrailsname);	
		        			
		        			if(arrayNewList.length!=0){
		        				arrayNewList=[];
		        				columnCont=[];
		        			layer.close(index); 
		        			}
    	        		  },
    	        		  btn2:function (index,layero){ 
      	        			
      	        			arrayNewList=[];
  		        			columnCont=[];
      	        			layer.close(index)
      	        			  
      	        		  }
    	        	});
    	        }
    	    });
			function saveData(obj){
				var rowData = $("#zjJobId").jqGrid("getRowData", obj);
	            arrayNewList.push(rowData.id);
	            columnCont.push(rowData.name);
	        }
	        function deleteIndexData(obj){
	        	var rowData = $("#zjJobId").jqGrid("getRowData", obj);
	            //获取obj在arrayNewList数组中的索引值
	            for(i = 0; i < arrayNewList.length; i++){
	                if (arrayNewList[i] == rowData.id){
	                    //根据索引值删除arrayNewList中的数据
	                	RemoveValByIndex(arrayNewList, i);
	                	RemoveValByIndex(columnCont, i);
	                    i--;
	                }
	             }
	        }
	        $("#zjJobId").jqGrid('clearGridData');
			$("#zjJobId").trigger('reloadGrid');
		},
	}
});
function RemoveValByIndex(arr, index) {
	  arr.splice(index, 1);
	}